//
//  DKCache.m
//  DKCacheDemo
//
//  Created by 王治恒 on 2018/6/26.
//  Copyright © 2018年 王治恒. All rights reserved.
//

#import "DKCache.h"
#import "DKLRUCache.h"

@interface DKCache()
{
    DKLRUCache *_lurCache;
}
@end

@implementation DKCache

static DKCache *cacheInstance;
+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cacheInstance = [[super alloc] superInit];
    });
    return cacheInstance;
}

- (instancetype)superInit
{
    _lurCache = [[DKLRUCache alloc] init];
    return [super init];
}

- (void)cacheObject:(id<NSCoding>)object forKey:(NSString *)key whenResult:(DKCacheObjectBlock)result
{
    [_lurCache cacheObject:object forKey:key];
    [[DKFileCache cacheWithName:key] cacheObject:object cacheResult:result];
}

- (void)cacheObject:(id<NSCoding>)object forKey:(NSString *)key andTiemLimit:(NSTimeInterval)timeLimit whenResult:(DKCacheObjectBlock)result
{
    [_lurCache cacheObject:object forKey:key];
    [[DKFileCache cacheWithName:key] cacheObject:object withTimeLimit:timeLimit cacheResult:result];
}

- (void)cacheObject:(id<NSCoding>)object forKey:(NSString *)key withSerialize:(DKCacheSerializeBlock)serialize andDeserialize:(DKCacheDeserializeBlock)deserialize whenResult:(DKCacheObjectBlock)result
{
    [_lurCache cacheObject:object forKey:key];
    [[DKFileCache cacheWithName:key serialize:serialize deserialize:deserialize] cacheObject:object cacheResult:result];
}

- (void)cacheObject:(id<NSCoding>)object forKey:(NSString *)key withTiemLimit:(NSTimeInterval)timeLimit andSerialize:(DKCacheSerializeBlock)serialize andDeserialize:(DKCacheDeserializeBlock)deserialize whenResult:(DKCacheObjectBlock)result
{
    [[DKFileCache cacheWithName:key serialize:serialize deserialize:deserialize] cacheObject:object withTimeLimit:timeLimit cacheResult:result];
}

- (void)objectForKey:(NSString *)key whenResult:(DKCacheGetObjectBlock)result
{
    id object = [_lurCache objectForKey:key];
    if (object) {
        result(object, key);
        return;
    } else {
        [[DKFileCache cacheWithName:key] object:^(id object, NSString *key) {
            if (object) {
             [self->_lurCache cacheObject:object forKey:key];
            }
            result(object, key);
        }];
    }

}

- (void)deleteObjectForKey:(NSString *)key whenResul:(DKCacheDeleteBlock)result
{
    [_lurCache removeForKey:key];
    [[DKFileCache cacheWithName:key] delete:result];
}

@end
